package jpf.nextsearch.util.validation.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jpf.nextsearch.exception.InitializationException;
import jpf.nextsearch.util.validation.base.GenericValidator;

/**
 * @author <a href="mailto:jacek.pruszkowski@gmail.com">Jacek Pruszkowski</a>
 * 
 */
public class RegexpValidator extends GenericValidator {

	private String rule;

	private Pattern pattern;

	@Override
	public void init() throws InitializationException {
		if (getRule() == null || getRule().length() == 0) {
			throw new InitializationException("RegexpValidator cannot be initialized. Rule is NULL ore empty");
		}
		pattern = Pattern.compile(getRule());
	}

	@Override
	protected boolean isValueValidInternal(Object value) {
		Matcher matcher = pattern.matcher((String) value);
		return matcher.matches();
	}

	@Override
	protected boolean supports(Class<?> klass) {
		return klass.isAssignableFrom(String.class);
	}

	public void setRule(String rule) {
		this.rule = rule;
	}

	public String getRule() {
		return rule;
	}

}
